package cemp.shiro;


import jakarta.servlet.Filter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * @author Yorke
 */
@Configuration
public class ShiroConfig {


    //开启shiro
//    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String,String> filterMap = new LinkedHashMap<>();


        Map<String, Filter> filters = new HashMap<>();
        /**
         * 创建一个AuthenticatingFilter 让所有请求都要经过shiro 过滤器
         * 主要重写的方法
         *
         */
        filters.put("oauth2", new OAuth2Filter());
        shiroFilterFactoryBean.setFilters(filters);


//        filterMap.put("/test/**","authc");
        filterMap.put("/auth/shiro/**", "anon");
        filterMap.put("/auth/security/**", "anon");
        filterMap.put("/**", "oauth2");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        //如果未认证会调整登录页面
        shiroFilterFactoryBean.setLoginUrl("/test/jwt/login");
//        shiroFilterFactoryBean.setLoginUrl("/test/login");
        //未授权会调整未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        return shiroFilterFactoryBean;
    }



    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager( ShiroCustomRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        securityManager.setRememberMeManager(null);
        return securityManager;
    }


}
